@file:OptIn(ExperimentalTvMaterial3Api::class)

package com.open.launcher

import android.os.Bundle
import android.view.KeyEvent
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.unit.Density
import androidx.navigation.NavController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Surface
import com.open.launcher.screen.AppScreen
import com.open.launcher.screen.MoviceScreen
import com.open.launcher.screen.MyScreen
import com.open.launcher.screen.TopBarScreen
import com.open.launcher.screen.TopBarTabs
import com.open.launcher.utils.KLog

@OptIn(ExperimentalFoundationApi::class)
@ExperimentalTvMaterial3Api
class MainActivity : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            Surface(modifier = Modifier.fillMaxSize()) {
                val displayMetrics = LocalContext.current.resources.displayMetrics
                val fontScale = LocalDensity.current.fontScale
                val density = displayMetrics.density
                val widthPixels = displayMetrics.widthPixels
                val widthDp = widthPixels / density
                val display = "density: $density\nwidthPixels: $widthPixels\nwidthDp: $widthDp"
                KLog.d("display:$display")
                CompositionLocalProvider(
                    LocalDensity provides Density(
                        density = widthPixels / 1920f,
                        fontScale = fontScale
                    )
                ) {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(color = colorResource(R.color.surface))
                    ) {
                        var currentDestination: String? by remember { mutableStateOf(null) }
                        val currentTopBarSelectedTabIndex by remember(currentDestination) {
                            derivedStateOf {
                                currentDestination?.let { TopBarTabs.indexOf(it) } ?: 1
                            }
                        }
                        val navController = rememberNavController()
                        // 标题栏的焦点下移到内容页面
                        val navHostFocusRequester = remember { FocusRequester() }

                        // 监听页面切换变化，根据tab的字符串 设置 Index，让白色移动块移动
                        DisposableEffect(Unit) {
                            val listener =
                                NavController.OnDestinationChangedListener { _, destination, _ ->
                                    currentDestination = destination.route
                                }
                            navController.addOnDestinationChangedListener(listener)
                            onDispose {
                                navController.removeOnDestinationChangedListener(listener)
                            }
                        }

                        // 内容显示(我的，影视，应用)
                        NavHost(
                            navController = navController,
                            startDestination = TopBarTabs[1],
                            builder = {
                                composable(TopBarTabs[0]) { // 我的
                                    MyScreen()
                                }
                                composable(TopBarTabs[1]) {// 影视
                                    MoviceScreen()
                                }
                                composable(TopBarTabs[2]) { // 应用
                                    AppScreen()
                                }
                            },
                            modifier = Modifier.focusRequester(navHostFocusRequester)
                        )

                        // 标题栏
                        TopBarScreen(
                            modifier = Modifier
                                .onSizeChanged { it.height }
                                .onKeyEvent {
                                    if (it.nativeKeyEvent.action == KeyEvent.ACTION_UP) {
                                        when (it.nativeKeyEvent.keyCode) {
                                            KeyEvent.KEYCODE_DPAD_DOWN -> {
                                                navHostFocusRequester.requestFocus()
                                            }
                                        }
                                    }
                                    false
                                },
                            selectedTabIndex = currentTopBarSelectedTabIndex
                        ) { index, title ->
                            navController.navigate(title) {
                                launchSingleTop = true
                            }
                        }

                    }
                }
            }
        }
    }

}